<?php 
class imageDAO extends CI_Model {


    function __construct()
    {
        // Call the Model constructor
        parent::__construct();

    }
    
    
    function save($url,$directorio)
    {
	$directorio = RUTA.$directorio;
	
	$referer = parse_url($url);
	$referer = $referer["scheme"]."://".$referer["host"];
	
	$opts = array(
		   'http'=>array(
		       'header'=>array("Referer: $referer\r\n")
		   )
	       );
	
	$context = stream_context_create($opts);
	
	$file = file_get_contents($url, false, $context);
	
	if($this->_save($file,$directorio))
	    return true;
	else
	    return false;

    }
       
       
    function _save ($file, $directorio)
    {
    	$file_info = new finfo(FILEINFO_MIME);	// object oriented approach!
	$mime_type = $file_info->buffer($file);  // e.g. gives "image/jpeg"
	 
	$mime_type = explode(";",$mime_type);
	$mime_type = $mime_type[0];
	
	/*
	Si el tama�o de la imagen es menor a 2K quiere decir que NO es una imagen
	*/
	if(round(strlen($file) / 1024, 2) < 3)
	    return false;
	
	
	$allowedMimes = array('image/tiff','image/bmp','image/jpeg','image/jpg', 'image/png', 'image/gif'); 
	
	if(in_array($mime_type, $allowedMimes)){
	    file_put_contents($directorio, $file);
	    return true;
	}else
	    return false;
	
    }	
       
       
    
 	
    function convert($user=array())
    {
		
		$default = array(
				"image"  => "",
				"width"  => '',
				"height" => ''
				 );

		$data = overwrite_array($default,$user);

		/*$data["image"] = BASE_PATH.$data["image"];
		
		if(!file_exists($data["image"]))
		    $data["image"] = BASE_PATH."img".DS."s.gif";
	

		$config['image_library']  = 'gd2';//quality
		$config['source_image']	  = $data["image"];
		$config['width']	  = $data["width"];
		
		if(isset($data['height']))
		$config['height']	  = $data['height'];
		
		$config['create_thumb']   = TRUE;
		$config['maintain_ratio'] = TRUE;
		$config['dynamic_output'] = TRUE;

		
		$this->load->library('image_lib',$config);
		
		//$this->image_lib->initialize($config); 
		$this->image_lib->resize();
    	*/
		$this->resize_crop($data['width'],$data['height'],$data['image']);
    }

	function ajustar($width = '', $height='0', $img = '')
    {

		$img = BASE_PATH.$img;
		
		if(!file_exists($img))
		    $img = BASE_PATH."img".DS."s.gif";
		
		list($srcwidth, $srcheight, $type, $attr) = getimagesize($img);
		/*if($srcwidth > $srcheight)
			$landscape = 1;
		else 
			$landscape = 0;
		*/
		if(empty($width) or $width== 0)
			$width = $srcwidth;
		#echo $img; die;
		$config['image_library'] = 'gd2';//quality
		$config['source_image']	= $img;
		
		$config['x_axis'] = ($srcwidth/2)-($width/2);
		$config['width'] = $width;
		$config['maintain_ratio'] = TRUE;
		
		#Si viene un alto especificado se hara un CROP
		if($height > 0){
			$config['height']	= $height;
			$config['y_axis'] = ($srcheight/2) - ($height/2);
			$config['maintain_ratio'] = FALSE;
		}
		#S solo viene el ancho, sacamos la proporcion del alto para hacer el RESIZE
		elseif($width > 0 and $height <= 0){
			$height = ($width*$srcheight)/$srcwidth;
		}
		
		#$config['create_thumb']   = TRUE;
		$config['dynamic_output'] = TRUE;

		
		$this->load->library('image_lib',$config);
		
		# si la imagen deseada es mas GRANDE que el original se hará un resize. Sino un crop
		if($height <= 0)
			$this->image_lib->resize();
		else
			$this->image_lib->crop();
		
    	$this->image_lib->clear(); 
		
    }


    
    function resize_crop($width = 0, $height = 0, $image_path) {
    	
		//$image_path = './media/k2/items/src/dc9e231f652301f80ea8e901bd9ec18a.jpg';

         //Get the Codeigniter object by reference
	    $CI = & get_instance();
	    
	    //Alternative image if file was not found
	    if (! file_exists($image_path))
	        $image_path =  BASE_PATH."img".DS."s.gif";
	       
	    //The new generated filename we want
	    $fileinfo = pathinfo($image_path);
	    $new_image_path = BASE_PATH . 'cache/' . $fileinfo['filename'] . '_' . $width . 'x' . $height . '.' . $fileinfo['extension'];
	    
	    //The first time the image is requested
	    //Or the original image is newer than our cache image
	    if ((! file_exists($new_image_path)) || filemtime($new_image_path) < filemtime($image_path)) {
	        $CI->load->library('image_lib');
	       
	        //The original sizes
	        $original_size = getimagesize($image_path);
	        $original_width = $original_size[0];
	        $original_height = $original_size[1];
	        $ratio = $original_width / $original_height;
	       
	        //The requested sizes
	        $requested_width = $width;
	        $requested_height = $height;
	       
	        //Initialising
	        $new_width = 0;
	        $new_height = 0;
	       
	        //Calculations
	        if ($requested_width > $requested_height) {
	            $new_width = $requested_width;
	            $new_height = $new_width / $ratio;
	            if ($requested_height == 0)
	                $requested_height = $new_height;
	           
	            if ($new_height < $requested_height) {
	                $new_height = $requested_height;
	                $new_width = $new_height * $ratio;
	            }
	       
	        }
	        else {
	            $new_height = $requested_height;
	            $new_width = $new_height * $ratio;
	            if ($requested_width == 0)
	                $requested_width = $new_width;
	           
	            if ($new_width < $requested_width) {
	                $new_width = $requested_width;
	                $new_height = $new_width / $ratio;
	            }
	        }
	       
	        $new_width = ceil($new_width);
	        $new_height = ceil($new_height);
	       
	        //Resizing
	        $config = array();
			
	        if (extension_loaded('imagick')) {
				$config['image_library'] = 'imagemagick';
				$config['library_path'] = '/usr/bin/';
			}
			else {
				$config['image_library'] = 'gd2';
			}
			
	        $config['source_image'] = $image_path;
	        $config['new_image'] = $new_image_path;
	        $config['maintain_ratio'] = FALSE;
	        $config['height'] = $new_height;
	        $config['width'] = $new_width;
	        $CI->image_lib->initialize($config);
	        $CI->image_lib->resize();
	        $CI->image_lib->clear();
	       
	        //Crop if both width and height are not zero
	        if (($width != 0) && ($height != 0)) {
	            $x_axis = floor(($new_width - $width) / 2);
	            //$y_axis = floor(($new_height - $height) / 2);
                    $y_axis = 0;
	           
	            //Cropping
	            $config = array();
	            $config['source_image'] = $new_image_path;
	            $config['maintain_ratio'] = FALSE;
	            $config['new_image'] = $new_image_path;
	            $config['width'] = $width;
	            $config['height'] = $height;
	            $config['x_axis'] = $x_axis;
	            $config['y_axis'] = $y_axis;
	            $CI->image_lib->initialize($config);
	            $CI->image_lib->crop();
	            $CI->image_lib->clear();
	        }
	    }
        
		
		
		$imagen = getimagesize($new_image_path);		
		header('Content-type: '.$imagen['mime']);
		
		readfile($new_image_path);
    }
    
}

?>